package cn.matezk.lianlian.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.matezk.lianlian.dao.DeviceDao;
import cn.matezk.lianlian.dto.DeviceDto;
import cn.matezk.lianlian.model.Device;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class QbFlowTask {
    @Autowired
    private DeviceDao deviceDao;
    private static final int PAGE_SIZE = 1000;
    private static final String API_BATCH = "https://api.tibiot.cn/api/v1/card/moreQueryCardInfo";
    private static final String ACCOUNT = "meitezhikong";
    private static final String PASSWORD = "Ww1234";

    @XxlJob("qbFlowSyncTask")
    public void flowSync() {
        int pageNo = 1;
        List<String> iccidList = new ArrayList<>();
        List<Device> updateDevs = new ArrayList<>();
        DeviceDto deviceDto = new DeviceDto();
        while (true) {
            deviceDto.setPageNo(pageNo ++);
            deviceDto.setPageSize(PAGE_SIZE);
            List<Device> devices = deviceDao.select(deviceDto);
            if (ObjectUtil.isNotEmpty(devices)) {
                for (Device dev : devices) {
                    if (ObjectUtil.isNotEmpty(dev.getIccid())) {
                        iccidList.add(dev.getIccid());
                    }
                }
            }
            if (ObjectUtil.isEmpty(devices) || devices.size() != PAGE_SIZE)
                break;
        }
        if (ObjectUtil.isNotEmpty(iccidList)) {
            List<List<String>> array = CollUtil.split(iccidList, 100);
            for (List<String> item : array) {
                try {
                    String tKey = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN);
                    String password = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(PASSWORD.getBytes()) + tKey).getBytes());
                    JSONObject object = JSONUtil.createObj()
                            .set("userName", ACCOUNT)
                            .set("passWord", password)
                            .set("tKey", tKey)
                            .set("cardType", 1)
                            .set("iccids", StrUtil.join(",", item).concat(","));
                    HttpResponse response = HttpRequest.post(API_BATCH)
                            .header("Content-Type", "application/json")
                            .body(object.toString())
                            .execute();
                    if (response.isOk()) {
                        JSONObject json = JSONUtil.parseObj(response.body());
                        if (json.getInt("status") == 0) {
                            JSONArray cards = json.getJSONArray("data");
                            for (int i = 0; i < cards.size(); i++) {
                                JSONObject card = cards.getJSONObject(i);
                                updateDevs.add(Device.buildCard("QB", card.getStr("iccid"), card.getDate("packageTime")));
                            }
                        }
                    }
                    response.close();
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
        }
        if (ObjectUtil.isNotEmpty(updateDevs)) {
            List<List<Device>> array = CollUtil.split(updateDevs, 500);
            for (List<Device> cs : array) {
                deviceDao.batchUpdateCardInfo(cs);
            }
        }
    }
}
